package com.ndood.gateway.app.mongo;

import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;

/**
 * https://blog.csdn.net/ln152315/article/details/78608499
 */
@Component
public class MongoDBAppender extends UnsynchronizedAppenderBase<LoggingEvent> implements ApplicationContextAware {
	
	private static MongoLogRepository mongoLogRepository;

	@Override
	public void start() {
		super.start();
	}

	@Override
	public void stop() {
		super.stop();
	}

	@Override
	protected void append(LoggingEvent e) {
		MongoLog mongoLog = new MongoLog();
		mongoLog.setLevel(e.getLevel().toString());
		mongoLog.setMsg(e.getFormattedMessage());
		mongoLog.setThread(e.getThreadName());
		mongoLog.setTs(new Date(e.getTimeStamp()));
		mongoLogRepository.save(mongoLog);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		if (applicationContext.getAutowireCapableBeanFactory().getBean(MongoLogRepository.class) != null) {
			mongoLogRepository = (MongoLogRepository) applicationContext.getAutowireCapableBeanFactory()
					.getBean(MongoLogRepository.class);
		}
	}
}
